# -*- coding: utf-8 -*-
import logging
import uuid
from datetime import date

from py_engine import session
from py_table import User

logger = logging.getLogger(__name__)


# Base = declarative_base()
# Base.metadata.reflect(bind=engine)
# tables = Base.metadata.tables


# class User(Base):
#     __table__ = tables['user']
#

def bulk_save():
    user_list = list()
    for i in range(100000):
        user_list.append(User(user_name=uuid.uuid4().hex, update_column=float(i), user_birthday=date.today()))
        pass

    logger.info('start')
    # session.add_all(user_list)
    # 批量保存
    session.bulk_save_objects(user_list)

    # session.add(User(user_name='chench', update_column=0.1))

    session.commit()
    logger.info('stop')


def bulk_insert():
    insert_list = list()

    json_dict = {'key': 'value'}

    for i in range(10000):
        insert_list.append({
            'user_name': uuid.uuid4().hex,
            'update_column': float(i),
            'user_birthday': date.today(),
            # 'json_column': {},
            'json_column': json_dict,
            'text_column': '{}',
            # 'text_column': 1.json.dumps(json_dict),
        })
        pass

    logger.info('start')

    session.bulk_insert_mappings(User, insert_list)
    session.commit()
    logger.info('stop')

    pass


def bulk_update():
    data = session.query(User).all()
    update_list = list()

    for item in data:
        update_list.append({
            'user_id': item.user_id,
            'user_name': item.user_name + 'q',
        })
        pass
    session.bulk_update_mappings(User, update_list)
    logger.info(f'update_length={len(update_list)}')

    session.commit()


if __name__ == '__main__':
    for _ in range(3):
        # bulk_save()
        bulk_insert()

    pass
